<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-04-12 18:47:17
 * @LastEditTime: 2023-04-06 17:08:30
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 新建 / 编辑 页面
 * @FilePath: \vue3-element-plus-web\src\views\SysManage\SysUser\components\Drawer\create.vue
 * Copyright 版权声明
-->
<template>
  <div class="">
    <el-form
      :rules="rules"
      ref="dataForm"
      :model="temp"
      label-width="160px"
      style='width:100%;'
    >
      <el-form-item label="用户编号：" prop="code">
        <el-input v-model="temp.code" placeholder="请输入用户编号"></el-input>
      </el-form-item>

      <!-- <el-form-item label="用户平台：" prop="userType">
        <el-input v-model="temp.userType" placeholder="请输入用户平台"></el-input>
      </el-form-item> -->

      <el-form-item label="账号：" prop="account">
        <el-input v-model="temp.account" placeholder="请输入账号"></el-input>
      </el-form-item>

      <template v-if="drawerType !== 'UPDATE'">
        <el-form-item label="密码：" prop="password">
          <el-input v-model="temp.password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </template>

      <el-form-item label="昵称：" prop="name">
        <el-input v-model="temp.name" placeholder="请输入昵称"></el-input>
      </el-form-item>

      <el-form-item label="角色：" prop="roleIdArr">
        <el-select
          multiple
          v-model="temp.roleIdArr"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="部门：" prop="deptIdArr">
        <el-cascader
          placeholder="请选择部门"
          v-model="temp.deptIdArr"
          :options="deptTreeData"
          :props="{ value: 'id', label: 'title', checkStrictly: true }"
          @change="handleDeptChange"></el-cascader>
      </el-form-item>

      <!-- <el-form-item label="岗位：" prop="postId">
        <el-input v-model="temp.postId" placeholder="请选择岗位"></el-input>
      </el-form-item> -->

      <el-form-item label="真实姓名：" prop="realName">
        <el-input v-model="temp.realName" placeholder="请输入真实姓名"></el-input>
      </el-form-item>

      <el-form-item label="头像：" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="'//192.168.0.19:20002/file/upload'"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadHttpRequest"
        >
          <img v-if="temp.avatar" :src="temp.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="temp.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>

      <el-form-item label="手机号码：" prop="phone">
        <el-input v-model="temp.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>

      <el-form-item label="生日：" prop="birthday">
        <el-date-picker
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          v-model="temp.birthday"
          type="date"
          placeholder="请选择生日"
        />
      </el-form-item>

      <el-form-item label="性别：" prop="sex">
        <el-select
          v-model="temp.sex"
          placeholder="请选择性别"
        >
          <el-option
            v-for="item in SEX_ENUM"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="IC卡ID(对接档案柜)：" prop="icCard">
        <el-input v-model="temp.icCard" placeholder="请输入IC卡ID(对接档案柜)"></el-input>
      </el-form-item>

      <el-form-item label="状态：" prop="status">
        <el-radio-group v-model="temp.status">
          <el-radio
            v-for="item in stateList"
            :key="item.value"
            :label="item.value">
            {{item.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { ENABLED_STATE_ENUM } from '@/config'
import { SEX_ENUM } from '@/config/views/SysManage/SysUser'
import { getList as getRoleList } from '@/api/SysManage/role'
import { getTree as getDeptTree } from '@/api/SysManage/dept'
import { fileUpload } from '@/api/upload'
import md5 from 'js-md5'
import { DonMessage } from '@/utils/DonMessage'
import { validatePssword } from '@/utils/validate'
// 图标组件
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'Create',
  computed: {
    ...mapGetters([
      'drawerCurrent',
      'token'
    ]),
    drawerType: function() {
      return this.drawerCurrent.drawerType
    }
  },
  components: {
    Plus
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (!validatePssword(value)) {
        callback(new Error('密码6-16位，必须包含：首字母大写、英文字母、特殊字符、数字'))
      } else {
        callback()
      }
    }
    return {
      temp: {
        avatar: '',
        deptId: '', // 部门ID
        status: 1
      },
      rules: {
        // code: [
        //   { required: true, message: '请输入用户编号', trigger: 'change' },
        //   { max: 50, message: '用户编号最大长度50位', trigger: 'change' }
        // ],
        // userType: [
        //   { required: true, message: '请输入用户平台', trigger: 'change' }
        // ],
        account: [
          { required: true, message: '请输入账号', trigger: 'change' },
          { max: 50, message: '账号最大长度50位', trigger: 'change' }
        ],
        password: [
          { required: true, trigger: 'change', validator: validatePass }
        ],
        name: [
          { required: true, message: '请输入昵称', trigger: 'change' },
          { max: 20, message: '昵称最大长度20位', trigger: 'change' }
        ],
        // realName: [
        //   { required: true, message: '请输入真实姓名', trigger: 'change' },
        //   { max: 20, message: '真实姓名最大长度20位', trigger: 'change' }
        // ],
        // avatar: [
        //   { required: true, message: '请上传头像', trigger: 'change' }
        // ],
        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'change' }
        // ],
        // phone: [
        //   { required: true, message: '请输入手机号码', trigger: 'change' }
        // ],
        // birthday: [
        //   { required: true, message: '请输入生日', trigger: 'change' }
        // ],
        // sex: [
        //   { required: true, message: '请选择性别', trigger: 'change' }
        // ],
        roleIdArr: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        deptIdArr: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ]
        // ,
        // postId: [
        //   { required: true, message: '请选择岗位', trigger: 'change' }
        // ],
        // icCard: [
        //   { required: true, message: '请输入IC卡ID(对接档案柜)', trigger: 'change' }
        // ]
      },
      // 状态列表
      stateList: ENABLED_STATE_ENUM,
      // 性别 枚举
      SEX_ENUM,
      // 当前部门信息
      currentDept: {},
      // 角色列表
      roleList: [],
      // 部门树数据
      deptTreeData: []
    }
  },
  watch: {
    // 表单内容体
    temp: {
      handler: function(val, oldVal) {
      },
      deep: true
    }
  },
  created() {
    // 列表传过来的数据
    const temp = this.drawerCurrent.params.row
    this.temp = Object.assign({}, this.temp, temp)
    // *******************如果是 【编辑】 需要从接口数据的话执行一下操作
    if (this.drawerType === 'UPDATE') {
      this.temp.roleIdArr = (this.temp.roleId || '').split(',')
      this.temp.deptIdArr = (this.temp.ancestors || '').split(',')
      // drawer loadding 状态 打开
      this.$store.dispatch('SetDrawerloading', true)
      setTimeout(() => {
        // drawer loadding 状态 关闭
        this.$store.dispatch('SetDrawerloading', false)
      }, 500)
    }

    if (this.drawerType === 'CREATE') {
      // 获取当前部门信息
      const currentDept = this.drawerCurrent.params.pageParams.currentDept || {}
      this.currentDept = currentDept
      if (this.currentDept.id) {
        this.temp.deptIdArr = (this.currentDept.ancestors || '').split(',')
      }
    }

    // 获取角色列表
    this.getRoleList()
    // 获取部门树
    this.getDeptTree()
  },
  mounted() {

  },
  methods: {
    // 重写上传
    async uploadHttpRequest(params) {
      const { file } = params
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 1)
      const res = await fileUpload(formData)
      if (res.code === 200) {
        this.temp.avatar = res.data
        this.$refs['dataForm'].clearValidate(['avatar'])
      } else {
        new DonMessage().error({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'png'
      const extension2 = testmsg === 'jpg'
      const extension3 = testmsg === 'jpeg'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2 && !extension3) {
        this.$message({
          message: '上传文件只能是 png、jpg、jpeg格式!请重新选择文件！',
          type: 'warning'
        })
        return false
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 5MB!',
          type: 'warning'
        })
        return false
      }
      return extension || extension2 || extension3 && isLt2M
    },
    // 部门改变
    handleDeptChange(val) {
      this.temp.deptId = val[val.length - 1]
    },
    // 获取部门树
    async getDeptTree() {
      const res = await getDeptTree()
      this.deptTreeData = res.data || []
    },
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleList({
        current: 1,
        size: 9999
      })
      this.roleList = res.data.records || []
    },
    // 提交表单
    submitForm() {
      return this.$refs['dataForm'].validate()
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.temp))
      data.roleId = data.roleIdArr.toString()
      if (this.drawerType === 'CREATE') {
        data.password = md5(data.password)
      }
      if (this.drawerType === 'UPDATE') {
        delete data.password
      }
      return data
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
